﻿using HomeCloudStorageSystem.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Security;
using HomeCloudStorageSystem.Helps;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using Microsoft.EntityFrameworkCore;
using HomeCloudStorageSystem.DataBase;
using HomeCloudStorageSystem.Dtos;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using HomeCloudStorageSystem.Models;

namespace HomeCloudStorageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class AvatarsController : ControllerBase
    {
        private readonly IAvatarsRepository _avatarsRepository;
        private readonly IUserRepository _userRepository;
        private readonly AppDbContext _context;
        public AvatarsController(IAvatarsRepository avatarsRepository, IUserRepository userRepository, AppDbContext context)
        {
            _avatarsRepository = avatarsRepository;
            _userRepository = userRepository;
            _context = context;
        }
        /// <summary>
        /// 上传用户头像
        /// </summary>
        /// <param name="file">用户头像参数</param>
        /// <returns>avatarsUrl</returns>
        [AllowAnonymous]
        [HttpPost]
        public IActionResult UploadAvatars(IFormFile file)
        {
            if (file == null)
            {
                return BadRequest("不能上传空文件");
            }
            string ex = Path.GetExtension(file.FileName);
            string fileName = Guid.NewGuid().ToString() + ex;
            string filePath = @"../../家庭云盘系统文件夹/用户头像/" + fileName;
            while (System.IO.File.Exists(filePath))
            {
                // 如果存在该图片，则重新命名
                fileName = Guid.NewGuid().ToString() + ex;
                filePath = @"../../家庭云盘系统文件夹/用户头像/" + fileName;
            }
            var avatarsUrl = HttpContext.Request.Scheme + @"://" + HttpContext.Request.Headers.Host + @"/api/Avatars/";
            string message = _avatarsRepository.SavaAvatars(file, filePath);
            if (message == "上传失败")
            {
                return BadRequest(message);
            }
            if (System.IO.File.Exists(filePath) && message == "上传成功")
            {
                avatarsUrl += fileName;
            }
            return Ok(JsonConvert.SerializeObject(avatarsUrl));
        }
        /// <summary>
        /// 修改头像
        /// </summary>
        /// <param name="file">新头像</param>
        /// <returns>修改成功信息</returns>
        [HttpPost("Update")]
        public IActionResult UpdateAvatars(IFormFile file)
        {
            if (file == null)
            {
                return BadRequest("错误的请求");
            }
            string userName = User.Claims.FirstOrDefault(n => n.Type == ClaimTypes.NameIdentifier)?.Value;
            var userInfo = _userRepository.GetUserByUserName(userName);
            string fileName = userInfo.HeadImag.Split('/').LastOrDefault();
            string filePath = @"../../家庭云盘系统文件夹/用户头像/" + fileName;
            if (System.IO.File.Exists(filePath))
            {
                //如果文件夹中已经有头像了，就将以前的头像删除后重新保存一个头像
                System.IO.File.Copy(filePath, filePath + ".test");
                System.IO.File.Delete(filePath);
            }
            // 重新构造新的文件夹路径，即使文件名相同，但存在扩展名不同的情况
            string newEx = file.FileName.Split('.').LastOrDefault();
            var newFileName = (fileName.Split('.').FirstOrDefault() ?? Guid.NewGuid().ToString()) + '.' + newEx;
            var newFilePath = @"../../家庭云盘系统文件夹/用户头像/" + newFileName;
            string message = _avatarsRepository.SavaAvatars(file, newFilePath);
            if (message == "上传失败")
            {
                return BadRequest(message);
            }
            //构造返回路径
            var avatarsUrl = HttpContext.Request.Scheme + @"://" + HttpContext.Request.Headers.Host + @"/api/Avatars/";
            if (System.IO.File.Exists(newFilePath) || message == "上传成功")
            {
                avatarsUrl += newFileName;
            }
            // 修改用户信息表中的头像地址
            var transaction = _context.Database.BeginTransaction();
            var user = new User();
            userInfo.HeadImag = avatarsUrl;
            user = userInfo;
            // 显示标记属性也被修改
            _context.Entry(user).State = EntityState.Modified;
            try
            {
                _context.SaveChanges();
                System.IO.File.Delete(filePath + ".test");
                transaction.Commit();
                transaction.Dispose();
            }
            catch
            {
                System.IO.File.Delete(newFilePath);
                System.IO.File.Copy(filePath + ".test", filePath);
                System.IO.File.Delete(filePath + ".test");
                transaction.Rollback();
                throw;
            }
            return Ok(JsonConvert.SerializeObject(avatarsUrl));
        }
        /// <summary>
        /// 获取用户头像
        /// </summary>
        /// <returns>用户头像图片</returns>
        [AllowAnonymous]
        [HttpGet("{fileName}")]
        public IActionResult DownloadAvatars()
        {
            //从请求路径中获取文件名
            string fileName = HttpContext.Request.Path.ToString().Split('/').LastOrDefault();
            string fileFullPath = @"../../家庭云盘系统文件夹/用户头像/" + fileName;
            if (!System.IO.File.Exists(fileFullPath))
            {
                return NotFound("没有找到数据");
            }
            var fileBytes = _avatarsRepository.Avatars(fileFullPath);
            var types = ReadStreamHelp.GetMimeTypes();
            var ex = Path.GetExtension(fileName).ToLowerInvariant();
            var contentType = types[ex];
            return File(fileBytes, contentType);
        }
        /// <summary>
        /// 删除头像
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{fileName}")]
        public IActionResult DeleteAvatars()
        {
            string fileName = HttpContext.Request.Path.ToString().Split('/').LastOrDefault();
            string fileFullPath = @"../../家庭云盘系统文件夹/用户头像/" + fileName;
            if (System.IO.File.Exists(fileFullPath))
            {
                System.IO.File.Delete(fileFullPath);
            }
            return Ok("删除成功");
        }
    }
}
